/*
 * FileCopier.java
 *
 * Created on 14 April 2007, 22:51
 *
 * To change this template, choose Tools | Template Manager
 * and open the template in the editor.
 */

package org.cardcopier.file;

import java.io.File;
import java.io.IOException;
import java.util.List;
import java.util.concurrent.CopyOnWriteArrayList;
import org.apache.log4j.Logger;

/**
 *
 * @author Mark
 */
public class FileCopier {
    
    private static final Logger LOGGER = Logger.getLogger(FileCopier.class);
    
    private final CopyOnWriteArrayList<FileCopierListener> listeners = new CopyOnWriteArrayList<FileCopierListener>();
    private final FileUtils fileUtils;
    private final boolean shouldDeleteSourceFileAfterCopy;

    private volatile boolean copyCancelled = false;
    
    public FileCopier(FileUtils fileUtils, boolean shouldDeleteSourceFileAfterCopy) {
        this.fileUtils = fileUtils;
        this.shouldDeleteSourceFileAfterCopy = shouldDeleteSourceFileAfterCopy;
    }

    public void copyFiles(List<FileState> files) throws IOException {
        LOGGER.info("Started file copy " + files.size() + " files");
        for (int i = 0; i < files.size() && !copyCancelled; i++) {
            FileState fileState = files.get(i);
            copyFile(i, fileState.getSourceFile(), fileState.getDestinationFile());
        }
        LOGGER.info("Finished file copy");
    }

    private void copyFile(final int fileIndex, final File sourceFile, final File destinationFile) throws IOException {
        LOGGER.info("[" + fileIndex + "] Copying  " + sourceFile.getAbsolutePath());
        LOGGER.info("[" + fileIndex + "]      to  " + destinationFile.getAbsolutePath());
        fireFileCopyStarted(sourceFile, destinationFile);
        fileUtils.copyFile(sourceFile, destinationFile);
        if (shouldDeleteSourceFileAfterCopy) {
            LOGGER.info("[" + fileIndex + "] Deleting " + sourceFile.getAbsolutePath());
            fileUtils.deleteFile(sourceFile);
        }
        fireFileCopyFinished(sourceFile, destinationFile);
    }
    
    public void cancelCopy() {
        LOGGER.info("Copy cancelled");
        this.copyCancelled = true;
    }
    
    public void addFileCopierListener(FileCopierListener fileCopierListener) {
        listeners.add(fileCopierListener);
    }
    
    public void removeFileCopierListener(FileCopierListener fileCopierListener) {
        listeners.remove(fileCopierListener);
    }
    
    private void fireFileCopyStarted(File sourceFile, File destinationFile) {
        for (FileCopierListener listener : listeners) {
            listener.fileCopyStarted(sourceFile, destinationFile);
        }
    }

    private void fireFileCopyFinished(File sourceFile, File destinationFile) {
        for (FileCopierListener listener : listeners) {
            listener.fileCopyFinished(sourceFile, destinationFile);
        }
    }
}
